<?php
namespace app\cash\controller;
use think\Controller;
use think\Db;
use app\cash\model\OrderDetails;
use app\cash\model\StoreGoodsLog;
class Index extends Controller{
    /**
     * @Author lignyun
     * @Desc    检查登录
     * 2018-04-09
     */
    public function _initialize(){
        if(!session('cash_user')) {
            $this->redirect('@cash/login/index');
        }
    }

    /**
     * 收银台
     * @return mixed
     * @throws \Exception
     * @throws \think\Exception
     */
    public function index()
    {
        $user = session('cash_user');

        if (request()->ispost()) {
            $post = input('post.');

            $post['nums'] = explode(',', $post['nums']);
            $post['goods'] = explode(',', $post['goods']);
            $post['price'] = explode(',', $post['prices']);
            $post['cat'] = explode(',', $post['cats']);

            $coupon_id = 0;//不使用优惠券

            $rate = 1;//默认折扣是1
            $total = $post['total'];//默认是原价
            if ($post['member']) {
                $member = db('user')->where('pay_code', $post['member'])->find();
                if (!$member)
                    $member = db('user')->where('mobile', $post['member'])->find();

                if ($member) {//定位到会员
                    if ($post['ycard']) {//使用优惠券
                        $ycard = db('view_user_ycard')->where('id', $post['ycard'])->find();//优惠券
                        $ymoney = 0;//符合优惠条件的金额
                        if ($ycard['cat_id'] === 0)//通用
                            $ymoney = $post['total'];
                        else//指定品类
                            foreach ($post['cat'] as $k => $v) {
                                if ($v == $ycard['cat_id'])
                                    $ymoney += $post['price'][$k] * $post['nums'][$k];
                            }
                        if ($ymoney < $ycard['morethan'])
                            return json(['code' => 0, 'msg' => '订单金额不足，无法使用该优惠券！']);
                        else{//使用优惠券
                            $coupon_id = $post['ycard'];
                            //计算优惠比例，优惠后价格/优惠前价格
                            $rate = ($ymoney-$ycard['reduce'])/$ymoney;
                            //计算优惠后的总价
                            $total = $post['total'] - $ycard['reduce'];
                            //更新优惠券为已使用
                            db('user_ycard')->update(['id'=>$post['ycard'], 'is_used'=>1]);
                        }
                    }
                    $uid = $member['uid'];
                    if ($post['method'] == 3 && $total > $member['user_money'])
                        return json(['code' => 0, 'msg' => '会员余额不足！']);
                } else
                    return json(['code' => 0, 'msg' => '会员卡号有误！']);

            } else
                $uid = 0;

            $num = array_sum($post['nums']);

            $sn = 'L' . build_order_no();
            //积分规则
            $sys_point = db('sys_point')->where('id',2)->find();
            $point_rate = $sys_point['point']/10;
            $sys_point2 = db('sys_point')->where('id',6)->find();
            $point_rate2 = $sys_point2['point']/10;

            //订单
            $point = ceil($total * $point_rate);
            $order = db('order')->insertGetid([
                'uid' => $uid,
                'coupon_id' => $coupon_id,
                'order_type' => 0,
                'order_sn' => $sn,
                'store_id' => $user['store_id'],
                'order_status' => 7,
                'pay_status' => 1,
                'pay_type' => $post['method'],
                'goods_price' => $post['total'],
                'final_amount' => $total,
                'receive_amount' => $post['receive'],
                'addtime' => time(),
                'pay_time' => time(),
                'goods_num' => $num,
                'score' => $point
            ]);

            $point_r = 1;//积分操作状态
            $user_money_r = 1;

            if ($uid > 0) {
                //扣余额
                if ($post['method'] == 3 && $total < $member['user_money']) {
                    $user_money = db('user')->where('uid', $uid)->setDec('user_money', $total);
                    $money_log = db('user_wallet_log')->insert([
                        'uid' => $uid,
                        'admin_id' => $user['id'],
                        'store_id' => $user['store_id'],
                        'order_id' => $order,
                        'pay_time' => time(),
                        'pay_status' => 1,
                        'amount' => -$total,
                        'cur_amount' => $member['user_money'] - $total,
                        'chargetype' => 1,
                        'addtime' => time()
                    ]);
                    if ($user_money === false || $money_log === false)
                        $user_money_r = 0;
                }


                $pay_points = db('user')->where('uid', $uid)->setInc('pay_points', $point);//权益积分
                $level_point = db('user')->where('uid', $uid)->setInc('level_point', $point);//等级积分

                //积分日志
                $point_log = db('user_point_log')->insert([
                    'uid' => $uid,
                    'admin_id' => session('user')['id'],
                    'store_id' => session('user')['store_id'],
                    'order_id' => $order,
                    'uidtype' => 1,
                    'type' => 1,
                    'point' => $point,
                    'curpoint' => $member['pay_points'] + $point,
                    'addtime' => time(),
                    'tuijianrenuid' => $member['pid']
                ]);

                $p = 1;
                if ($member['pid'] > 0) {
                    $point2 = $point * $point_rate2 / $point_rate;
                    //推荐人
                    $pm = db('user')->where('uid', $member['pid'])->find();
                    //积分日志
                    $point_log2 = db('user_point_log')->insert([
                        'uid' => $member['pid'],
                        'admin_id' => session('user')['id'],
                        'store_id' => session('user')['store_id'],
                        'order_id' => $order,
                        'uidtype' => 3,
                        'type' => 1,
                        'point' => $point2,
                        'curpoint' => $pm['pay_points'] + $point2,
                        'addtime' => time(),
                    ]);
                    $pay_points_p = db('user')->where('uid', $member['pid'])->setInc('pay_points', $point2);//权益积分
                    $level_point_p = db('user')->where('uid', $member['pid'])->setInc('level_point', $point2);//等级积分

                    if ($point_log2 === false || $pay_points_p === false || $level_point_p === false)
                        $p = 0;
                }

                if ($pay_points === false || $level_point === false || $point_log === false || $p === 0)
                    $point_r = 0;//积分失败
            }


            foreach ($post['nums'] as $k => $v) {
                $goods_stock = db('store_goods_stock')->find($post['goods'][$k]);
                $goods = db('goods')->find($goods_stock['goods_id']);

                $details[] = [
                    'uid' => $uid,
                    'order_id' => $order,
                    'spec_id' => $goods_stock['goods_spec_id'],
                    'spec_detail' => $goods_stock['spec_title'],
                    'goods_id' => $goods_stock['goods_id'],
                    'goods_num' => $v,
                    'spec_price' => $post['price'][$k] * $rate,
                    'final_amount' => $post['price'][$k] * $v * $rate,
                    'status' => 7,
                    'storeid' => $user['store_id'],
                    'is_online' => 0,
                    'addtime' => time()
                ];

                db('store_goods_stock')->where('id', $post['goods'][$k])->setDec('stock', $v);
                $cur_stock = db('store_goods_stock')->where('id', $post['goods'][$k])->find()['stock'];

                $log[] = [
                    'goods_id' => $goods_stock['goods_id'],
                    'goods_spec_id' => $goods_stock['goods_spec_id'],
                    'title' => $goods_stock['spec_title'],
                    'order_id' => $order,
                    'store_id' => $user['store_id'],
                    'chuku_num' => $v,
                    'remark' => $sn,
                    'cur_stock' => $cur_stock,
                    'addtime' => time()
                ];

                $order_list[] = [
                    'name' => $goods['name'] . ' ' . $goods_stock['spec_title'],
                    'num' => $v,
                    'price' => $post['price'][$k] * $rate,
                    'amount' => $post['price'][$k] * $v * $rate,
                ];
            }
            //出库记录
            $store_goods_log = new StoreGoodsLog();
            $orser_details = $store_goods_log->saveAll($log);

            //订单详情
            $order_details = new OrderDetails();
            $goods_log = $order_details->saveall($details);

            //订单动作
            $order_action = db('order_action')->insert([
                'uid' => $uid,
                'order_id' => $order,
                'action_user' => $user['id'],
                'storeid' => $user['store_id'],
                'status_desc' => '收银台交易完成',
                'addtime' => time(),
            ]);



//            //小票内容
            $content = '';

            $content .= '<tr><td colspan="4" style="font-size: large;text-align: center">一朵</td></tr><tr><td colspan="4" style="font-size: large;text-align: center">&nbsp;</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">单号 ' . $sn . '</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">收银员 ' . $user['id'] . '</td></tr><tr><td colspan="4" style="text-align: center">———————————————</td></tr><tr><td style="width: 25mm;">商品</td><td>数量</td><td>单价</td><td>小计</td></tr>';
            foreach ($order_list as $k => $v) {
                $content .= '<tr style="font-size: smaller;"><td colspan="4" style="text-align: left">' . $v['name'] . '</td></tr>';
                $content .= '<tr style="font-size: smaller;"><td style="width: 25mm"></td><td>' . $v['num'] . '</td><td>' . floatval($v['price']) . '</td><td>' . $v['amount'] . '</td></tr>';
            }
            $content .= '<tr><td colspan="4" style="text-align: center">———————————————</td></tr>';

            switch ($post['method']) {
                case 1:
                    $method = '支付宝';
                    break;
                case 2:
                    $method = '微信';
                    break;
                case 3:
                    $method = '余额';
                    break;
                case 4:
                    $method = '现金';
                    break;
                case 5:
                    $method = '银行卡';
                    break;
            }
            $content .= '<tr><td colspan="4" style="text-align: left;font-size: smaller">总数量：' . $num . ' ' . $method . '：￥' . $total . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
            $content .= '<tr><td colspan="4" style="text-align: left">' . '欢迎您再次光临' . '</td></tr>';
            $content .= '<tr><td colspan="4" style="text-align: left">' . date('Y-m-d H:i:s') . '</td></tr>';

            $receipt = db('order')->update(['id' => $order, 'receipt' => $content]);

            if ($goods_log !== false && $orser_details !== false && $order_action !== false && $order && $receipt !== false && $point_r === 1 && $user_money_r === 1)
//                return json(['code' => 1, 'msg' => '结账成功！', 'data' => $content]);
                return json(['code' => 1, 'msg' => '结账成功！', 'data' => $content]);

        } else {
            $store = db('store')->where('id',$user['store_id'])->find();
//            $join = [
//                ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
//                ['ys_goods_spec_detail s', 'a.goods_spec_id=s.id', 'LEFT'],
//            ];
            $goods_category = db('goods_category')->where(['is_exp'=>0,'status'=>1,'is_deleted'=>0])->select();
//            $goods = db('store_goods_stock')->alias('a')->join($join)->where('a.store_id',$user['store_id'])->field('a.*,g.name,s.price,s.member_price,g.member_level_id,s.title,a.stock,a.trim_price,g.cat_id')->select();
//            foreach ($goods as $k => &$v) {
//                if ($v['is_spec'] == 1)
//                    $v['price'] = db('goods_spec_detail')->where('id', $v['goods_spec_id'])->find()['price'];
//                else
//                    $v['price'] = db('goods_spec_detail')->where('goods_id', $v['goods_id'])->where('specs', 0)->find()['price'];
//            }
            $this->assign('count_category',count($goods_category));
            $this->assign('goods_category',$goods_category);
            $this->assign('store', $store);
            $this->assign('user', $user);
//            $this->assign('goods', $goods);
            $this->assign('title', '收银台');

            return view();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    支付订单
     * array(3) {
        ["pay_type"] => string(1) "2"
        ["nums"] => array(2) {
        [0] => string(1) "1"
        [1] => string(1) "1"
        }
        ["ids"] => array(2) {
        [0] => string(2) "16"
        [1] => string(2) "18"
        }
     }
     * 2018-05-08
     */
    public function pay_order(){
        $post = input('post.');
        $store_id = session('cash_user.store_id');
        $order_sn = 'L'.build_order_no().$store_id;     //订单编号
        $store = db('store')->where('id',$store_id)->find();            //查询门店信息，判断是否开启调价功能
        $member = db('user')->where('uid',$post['uid'])->find();
        $goods_num = array_sum($post['nums']);
        $goods = db('store_goods_stock')->alias('a')->join('ys_goods_spec_detail b','a.goods_spec_id=b.id','LEFT')->where('a.id','in',$post['ids'])->join('ys_goods c','a.goods_id=c.id','LEFT')->field('a.id,a.goods_spec_id,a.stock,b.title,b.goods_id,a.trim_price,b.price,b.member_price,c.name')->select();

        $order_details_arr = [];
        $final_amount = 0;
        $store_goods_stock_arr = [];        //门店商品库存信息

        if($post['pay_type'] == 3 || $post['pay_type'] == 4 || $store['is_jiameng'] == 1){             //余额支付
            $status = 4;
            $action = '订单已完成';
            $pay_status = 1;
            $pay_time = time();
        }else{
            $status = 0;
            $action = '订单待支付';
            $pay_status = 0;
            $pay_time = time();
        }

        if($post['pay_type'] == 3 || $post['pay_type'] == 4 || $store['is_jiameng'] == 1){
            //小票内容
            $content = '';
            $content .= '<tr><td colspan="4" style="font-size: large;text-align: center">'.$store["title"].'</td></tr><tr><td colspan="4" style="font-size: large;text-align: center">&nbsp;</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">单号 ' . $order_sn . '</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">收银员 ' . session("cash_user")["realname"] . '</td></tr><tr><td colspan="4" style="text-align: center">———————————————</td></tr><tr><td style="width: 25mm;">商品</td><td>数量</td><td>单价</td><td>小计</td></tr>';
        }


        foreach($goods as $k => $v){            //构建订单详情数据
            if($store['price_status'] == 1 && $v['trim_price'] != 0){     //使用线下调价
                $order_details_arr[$k]['spec_price'] = $v['trim_price'];
                $order_details_arr[$k]['discount_signal_price'] = $v['trim_price'];
                $order_details_arr[$k]['final_amount'] = $post['nums'][$k]*$v['trim_price'];
                $order_details_arr[$k]['discount_signal_price'] = $v['trim_price'];
                $final_amount += $post['nums'][$k]*$v['trim_price'];
            }else{
                $order_details_arr[$k]['spec_price'] = $v['price'];
                $order_details_arr[$k]['discount_signal_price'] = $v['price'];
                $order_details_arr[$k]['final_amount'] = $post['nums'][$k]*$v['price'];
                $order_details_arr[$k]['discount_signal_price'] = $v['price'];
                $final_amount += $post['nums'][$k]*$v['price'];
            }

            $order_details_arr[$k]['uid'] = $post['uid'];
            $order_details_arr[$k]['spec_id'] = $v['goods_spec_id'];
            $order_details_arr[$k]['spec_detail'] = $v['title'];
            $order_details_arr[$k]['goods_id'] = $v['goods_id'];
            $order_details_arr[$k]['goods_num'] = $post['nums'][$k];
            $order_details_arr[$k]['is_online'] = 0;
            $order_details_arr[$k]['store_goods_stock_id'] = $v['id'];
            $order_details_arr[$k]['addtime'] = time();
            $order_details_arr[$k]['status'] = $status;
            $order_details_arr[$k]['storeid'] = $store_id;

            //门店库存记录数据
            $store_goods_stock_arr[$k]['goods_id'] = $v['goods_id'];
            $store_goods_stock_arr[$k]['goods_spec_id'] = $v['goods_spec_id'];
            $store_goods_stock_arr[$k]['title'] = $v['title'];
            $store_goods_stock_arr[$k]['store_id'] = $store['id'];
            $store_goods_stock_arr[$k]['order_id'] = '';
            $store_goods_stock_arr[$k]['types'] = 2;
            $store_goods_stock_arr[$k]['ruku_num'] = 0;
            $store_goods_stock_arr[$k]['tuihuo_num'] = 0;
            $store_goods_stock_arr[$k]['chuku_num'] = $post['nums'][$k];
            $store_goods_stock_arr[$k]['sunhao_num'] = 0;
            $store_goods_stock_arr[$k]['remark'] = '售卖'.$post['nums'][$k];
            $store_goods_stock_arr[$k]['cur_stock'] = $v['stock'] - $post['nums'][$k];
            $store_goods_stock_arr[$k]['addtime'] = time();
            $store_goods_stock_arr[$k]['order_sn'] = $order_sn;


//            $store_goods_stock_arr = [
//                'goods_id'=>$v['goods_id'],
//                'goods_spec_id'=>$v['goods_spec_id'],
//                'title'=>$v['title'],
//                'order_id'=>'',
//                'store_id'=>$store['id'],
//                'types'=>2,
//                'ruku_num'=>0,
//                'tuihuo_num'=>0,
//                'chuku_num'=>$post['nums'][$k],
//                'sunhao_num'=>0,
//                'remark'=>'售卖'.$post['nums'][$k],
//                'cur_stock'=>$v['stock'] - $post['nums'][$k],
//                'addtime'=>time(),
//                'order_sn'=>$order_sn
//            ];

            if($post['pay_type'] == 3 || $post['pay_type'] == 4 || $store['is_jiameng'] == 1){
                $content .= '<tr style="font-size: smaller;"><td colspan="4" style="text-align: left">' . $v['name'].$v['title'] . '</td></tr>';
                $content .= '<tr style="font-size: smaller;"><td style="width: 25mm"></td><td>' . $post['nums'][$k] . '</td><td>' . floatval($order_details_arr[$k]['spec_price']) . '</td><td>' . $order_details_arr[$k]['spec_price']*$post['nums'][$k] . '</td></tr>';

            }
        }

        //使用改价
        if($final_amount != $post['final_amount']){
            $final_amount = $post['final_amount'];
        }

        if($post['pay_type'] == 3 || $post['pay_type'] == 4 || $store['is_jiameng'] == 1){
            $content .= '<tr><td colspan="4" style="text-align: center">———————————————</td></tr>';

            switch ($post['pay_type']) {
                case 1:
                    $method = '支付宝';
                    break;
                case 2:
                    $method = '微信';
                    break;
                case 3:
                    $method = '余额';
                    break;
                case 4:
                    $method = '现金';
                    break;
                case 5:
                    $method = '银行卡';
                    break;
                default:
                    break;
            }
//            $content .= '<tr><td colspan="4" style="text-align: center">———————————————</td></tr>';

            $content .= '<tr><td colspan="4" style="text-align: left;font-size: smaller">总数量：' . $goods_num . ' ' . $method . '：￥' . $final_amount . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
            $content .= '<tr><td colspan="4" style="text-align: left">' . '欢迎您再次光临' . '</td></tr>';
            $content .= '<tr><td colspan="4" style="text-align: left">' . date('Y-m-d H:i:s') . '</td></tr>';
        }
        if($post['pay_type'] == 3){
            $member = db('user')->where('pay_code',$post['mobile'])->find();
            if (!$member){
                $member = db('user')->where('mobile', $post['mobile'])->find();
            }
            if(empty($member)){
                $this->error('找不到会员信息，请重新查询会员信息','');
            }
            if($member['user_money'] < $final_amount){      //金额不足
                $this->error('余额不足，不能支付','');
            }
//            if($member['user_money'] < $final_amount){      //金额不足
//                $this->error('余额不足，不能支付','');
//            }
        }



        $order_arr = [
            'uid'=>$post['uid'],
            'coupon_id'=>0,
            'coupon_price'=>0,
            'cash_coupon_id'=>0,
            'cash_coupon_price'=>0,
            'order_type'=>0,
            'order_sn'=>$order_sn,
            'store_id'=>$store_id,
            'order_status'=>$status,
            'shipping_status'=>1,
            'cashier'=>session('cash_user')['id'],
//            'mobile'=>$member['mobile'],
            'pay_type'=>$post['pay_type'],
            'pay_status'=>$pay_status,
            'pay_time'=>$pay_time,
            'goods_num'=>$goods_num,
            'goods_price'=>$final_amount,
            'final_amount'=>$final_amount,
            'remark'=>$action,
            'addtime'=>time(),
        ];
        $order_id = db('order')->insertGetId($order_arr);

        foreach($order_details_arr as $k => $v){
            $order_details_arr[$k]['order_id'] = $order_id;
            $store_goods_stock_arr[$k]['order_id'] = $order_id;
        }
        db('order_details')->insertAll($order_details_arr);         //新增订单详情


        $order_action = [
            'uid'=>$post['uid'],
            'order_id'=>$order_id,
            'action_user'=>0,
            'order_status'=>$status,
            'pay_status'=>$pay_status,
            'status_desc'=>$action,
            'storeid'=>$store_id,
            'addtime'=>time()
        ];



        db('order_action')->insert($order_action);          //插入订单动作信息



//        third_tier_distribution($post['uid'],$final_amount,$store_id,$order_id,$money=0,$order_sn);


        if($post['pay_type'] == 3 || $post['pay_type'] == 4){         //余额支付
            $pay_log_arr = [
                'order_id'=>$order_id,
                'order_sn'=>$order_sn,
                'order_type'=>2,
                'uid'=>$post['uid'],
                'store_id'=>$store_id,          //门店id
                'pay_type'=>$post['pay_type'],
                'pay_sign'=>1,
                'amount'=>$final_amount,
                'remark'=>'线下购买商品，订单号'.$order_sn.'，总价：'.$final_amount,
                'addtime'=>time()
            ];
            db('pay_log')->insert($pay_log_arr);            //新增支付记录
            db('store')->where('id',$store_id)->setInc('user_money',$final_amount);     //更新门店会员卡金额数量
            //更新商品库存
            foreach($store_goods_stock_arr as $k => $v){
                db('store_goods_stock')->where(['goods_id'=>$v['goods_id'],'goods_spec_id'=>$v['goods_spec_id'],'store_id'=>$v['store_id'],'is_deleted'=>0])->setDec('stock',$v['chuku_num']);
            }
            db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志
            if($post['pay_type'] == 3){
                db('user')->where('uid',$post['uid'])->setDec('user_money',$final_amount);
                $data_wallet_arr = [
                    'uid'=>$post['uid'],
                    'admin_id'=>0,
                    'store_id'=>$store_id,
                    'order_id'=>$order_id,
                    'order_sn'=>$order_sn,
                    'pay_time'=>time(),
                    'pay_status'=>1,
                    'pay_type'=>3,
                    'amount'=>$final_amount,
                    'cur_amount'=>$member['user_money']-$final_amount,
                    'sign'=>2,
                    'chargetype'=>1,
                    'charge_cn'=>'支付订单',
                    'addtime'=>time()
                ];
                //记录余额记录
                db('user_wallet_log')->data($data_wallet_arr)->insert();       //记录余额记录
            }

            third_tier_distribution($post['uid'],$final_amount,$store_id,$order_id,0,$order_sn);           //三级分销返积分
            $this->success(3,'',$content);
        }else if($post['pay_type'] == 1 && $store['is_jiameng'] == 0){           //支付宝
            $pay_result = $this->redirect(url('Alipay/pay').'?order_id='.$order_id."&auth_code=".$post['auth_code']);
            if($pay_result['code'] == 1){           //支付成功
                $this->euccess(1,'',$content);
            }else{
                $this->error($pay_result['msg'],'');
            }
        }else if($post['pay_type'] == 2 && $store['is_jiameng'] == 0){          //微信支付
            $pay_result = $this->redirect(url('Wxpay/pay').'?order_id='.$order_id."&auth_code=".$post['auth_code']);
            if($pay_result['code'] == 1){           //支付成功
                $this->euccess(1,'',$content);
            }else{
                $this->error($pay_result['msg'],'');
            }
        }else if($post['pay_type'] == 1 && $store['is_jiameng'] == 1){          //加盟店
            $pay_log_arr = [
                'order_id'=>$order_id,
                'order_sn'=>$order_sn,
                'order_type'=>2,
                'uid'=>$post['uid'],
                'store_id'=>$store_id,          //门店id
                'pay_type'=>$post['pay_type'],
                'pay_sign'=>1,
                'amount'=>$final_amount,
                'remark'=>'线下购买商品，订单号'.$order_sn.'，总价：'.$final_amount,
                'addtime'=>time()
            ];
            db('pay_log')->insert($pay_log_arr);            //新增支付记录
            db('store')->where('id',$store_id)->setInc('user_money',$final_amount);     //更新门店会员卡金额数量
            //更新商品库存
            foreach($store_goods_stock_arr as $k => $v){
                db('store_goods_stock')->where(['goods_id'=>$v['goods_id'],'goods_spec_id'=>$v['goods_spec_id'],'store_id'=>$v['store_id'],'is_deleted'=>0])->setDec('stock',$v['chuku_num']);
            }
            db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志


            third_tier_distribution($post['uid'],$final_amount,$store_id,$order_id,0,$order_sn);           //三级分销返积分
            $this->success(3,'',$content);
        }else if($post['pay_type'] == 2 && $store['is_jiameng'] == 1){          //加盟店
            $pay_log_arr = [
                'order_id'=>$order_id,
                'order_sn'=>$order_sn,
                'order_type'=>2,
                'uid'=>$post['uid'],
                'store_id'=>$store_id,          //门店id
                'pay_type'=>$post['pay_type'],
                'pay_sign'=>1,
                'amount'=>$final_amount,
                'remark'=>'线下购买商品，订单号'.$order_sn.'，总价：'.$final_amount,
                'addtime'=>time()
            ];
            db('pay_log')->insert($pay_log_arr);            //新增支付记录
            db('store')->where('id',$store_id)->setInc('user_money',$final_amount);     //更新门店会员卡金额数量
            //更新商品库存
            foreach($store_goods_stock_arr as $k => $v){
                db('store_goods_stock')->where(['goods_id'=>$v['goods_id'],'goods_spec_id'=>$v['goods_spec_id'],'store_id'=>$v['store_id'],'is_deleted'=>0])->setDec('stock',$v['chuku_num']);
            }
            db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志


            third_tier_distribution($post['uid'],$final_amount,$store_id,$order_id,0,$order_sn);           //三级分销返积分
            $this->success(3,'',$content);
        }


    }

    /**
     * 获取会员信息
     * @return mixed
     */
    private function member_old(){
        $store_id = session('user')['store_id'];
        $post = input();
        $member = db('user')->where('pay_code',$post['no'])->find();
//        halt($member);
        if (!$member)
            $member = db('user')->where('mobile', $post['no'])->find();
        $ycard = db('view_user_ycard')->where('uid', $member['uid'])->where('store_id', $store_id)->where('use_start_time', '<', time())->where('use_end_time', '>', time())->where('is_used', 0)->select();
        if ($member)
            return json([
                'name' => $member['realname'],
                'balance' => $member['user_money'],
                'ycard' => $ycard
            ]);
        else
            return json([
                'name' => '未找到该会员信息！',
                'balance' => '0.00',
                'ycard' => ''
            ]);
    }

    /**
     * @Author  lingyun
     * @Desc    获取会员信息
     * 2018-05-08
     */
    public function member(){
        $store_id = session('user')['store_id'];
        $post = input();
        $member = db('user')->where('pay_code',$post['no'])->find();
        if (!$member)
            $member = db('user')->where('mobile', $post['no'])->find();
//        $ycard = db('view_user_ycard')->where('uid', $member['uid'])->where('store_id', $store_id)->where('use_start_time', '<', time())->where('use_end_time', '>', time())->where('is_used', 0)->select();
        if ($member){
            $data = [
                'status'=>1,
                'name' => $member['realname'],
                'balance' => $member['user_money'],
                'realname' => $member['realname'],
                'mobile' => $member['mobile'],
                'uid' => $member['uid'],
            ];
            $this->success('查询成功','',$data);
        }else{
            $data = [
                'status'=>0,
                'name' => '未找到该会员信息！',
                'balance' => '0.00',
                'mobile'=>'',
                'realname'=>'',
                'uid'=>''
            ];
            $this->error('查询失败','',$data);
        }

    }

    /**
     * @Author  lingyun
     * @Desc    查询商品
     * @return \think\response\Json
     * 2018-04-09
     */
    public function findGoods()
    {
        $store_id = session('cash_user')['store_id'];
        $post = input('post.');

        if (!isset($post['id'])) {
            $post['keywords'];
            $db = db('view_store_goods')->where('store_id', $store_id)->where('name|good_number', 'like', '%' . $post['keywords'] . '%')->select();
            return json(['data' => $db]);
        } else {
            $db = db('view_store_goods')->where('id', $post['id'])->find();
            $store = db('store')->find($store_id);
            if ($store['price_status'] == 1 && $db['trim_price'] > 0) {
                $begin = strtotime(date('H:i:s', $store['begin']));
                $end = strtotime(date('H:i:s', $store['end']));
                if (time() > $begin && time() < $end)
                    $db['price'] = $db['trim_price'];
            }
            return json(['data' => $db]);
        }
    }

    /**
     * @Author  lingyun
     * @Desc    会员充值
     * 2018-04-09
     */
    public function recharge(){
        return $this->fetch();
    }

    /**
     * @Author  lingyun
     * @Desc    打印页面
     * 2018-04-25
     */
    public function order_print(){
        $order_id = input('order');


        return $this->fetch('print');
    }



    public function printss(){
        return $this->fetch('print2');
    }

    /**
     * @Author  lingyun
     * @Desc    根据商品分类找到商品信息
     * 2018-05-08
     */
    public function get_goods(){
        $cat_id = input('cat_id');
        $user = session('cash_user');
        $store = db('store')->where('id',$user['store_id'])->find();
        $join = [
            ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
            ['ys_goods_spec_detail s', 'a.goods_spec_id=s.id', 'LEFT'],
        ];
        $goods = db('store_goods_stock')->alias('a')->join($join)->where(['a.store_id'=>$user['store_id'],'g.cat_id'=>$cat_id,'a.stock'=>['gt',0]])->field('a.*,g.name,s.price,s.member_price,g.member_level_id,s.title,a.stock,a.trim_price,g.cat_id')->where(['a.onsale'=>1,'a.is_deleted'=>0])->order('s.price asc')->select();
        foreach($goods as $k => $v){
            $goods[$k]['name'] = mb_substr($v['name'],0,10,'utf-8');
            $goods[$k]['spec_title'] = mb_substr($v['spec_title'],0,20,'utf-8');
            if($store['price_status'] == 1 && $v['trim_price'] != 0){
                $goods[$k]['price'] = $v['trim_price'];
            }
        }
        if(!empty($goods)){
            $this->success('找到商品','',$goods);
        }else{
            $this->error('找不到商品信息','','');
        }
    }

    /**
     * 退出登录
     */
    public function out()
    {
//        if (session('cash_user')) {
//            LogService::write('系统管理', '用户退出系统成功');
//        }
        session('cash_user', null);
        //@lingyun   2018-04-09  防止销毁session  start
//        session_destroy();
        //@lingyun   2018-04-09  防止销毁session  end

        $this->success('退出登录成功！', '@cash/login');
    }


}
